import { showToast } from "vant"
import SystemDataManagementClass from "./SystemDataManagement"
import {
	DB,
	lumpSumCarFareLibraryKey,
	travelAddressLibraryKey,
	travelPeopleLibraryKey,
	travelRecordLibraryKey,
} from "@/assets/global"
import { TTravelInfo } from "../AddTravelRecord/AddTravelRecord"

import TravelRecordLibraryStore from "@/store/TravelRecordLibraryStore"
import _ from "lodash"
import * as indexedDB from "@utility/indexedDB"
const store = TravelRecordLibraryStore()

const clearDatabaseUtil = async (
	main: SystemDataManagementClass
): Promise<void> => {
	try {
		// 1. 校验输入
		if (main.selectProject.length === 0) {
			showToast("请选择清空项目。")
			return
		}

		// 2. 定义数据处理器（避免重复代码）
		const handlers: Record<string, () => Promise<any> | any> = {
			[travelRecordLibraryKey]: async () =>
				await indexedDB.clearAll(DB.store.TravelRecord.name),
			[travelPeopleLibraryKey]: () => (store.PeopleLibrary = []),
			[travelAddressLibraryKey]: () => (store.AddressLibrary = []),
			[lumpSumCarFareLibraryKey]: () => (store.LumpSumCarFareLibrary = []),
		}

		// 3. 并行执行清空操作（无需返回值）
		await Promise.all(
			main.selectProject.map(async (item: string) => {
				const handler = handlers[item]
				if (handler) {
					await handler()
				}
			})
		)

		// 4. 清空后刷新状态
		main.selectProject = []
		showToast("清空操作完成")
	} catch (error) {
		console.error("清空数据库失败:", error)
		showToast("清空操作失败")
	}
}

export default clearDatabaseUtil
